package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Visitors;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveVisitor(Visitors visitors) {
        if (visitors.getUserId() != null && visitors.getVisitorUserId() != null) {
            visitors.setId(ObjectId.get());
            visitors.setDate(System.currentTimeMillis());
            mongoTemplate.save(visitors);
            return visitors.getId().toHexString();
        }
        return null;
    }

    @Override
    public List<Visitors> topVisitor(Long userId, Integer num) {
        Query query = Query.query(Criteria.where("userId")
                .is(userId)).limit(num).with(Sort.by(Sort.Order.desc("date")));

        return topVisitor(query);
    }

    @Override
    public List<Visitors> topVisitor(Long userId, Long date) {
        Query query = Query.query(Criteria.where("userId")
                .is(userId).and("date").gt(date)).with(Sort.by(Sort.Order.desc("date")));

        return topVisitor(query);
    }

    private List<Visitors> topVisitor(Query query) {
        List<Visitors> visitors = this.mongoTemplate.find(query, Visitors.class);
        for (Visitors visitor : visitors) {
            Query query1 = Query.query(Criteria.where("userId")
                    .is(visitor.getVisitorUserId()).and("toUserId").is(visitor.getUserId()));
            RecommendUser one = this.mongoTemplate.findOne(query1, RecommendUser.class);
            if (one != null) {
                visitor.setScore(one.getScore());
            } else {
                visitor.setScore(30d);
            }
        }
        return visitors;
    }
}